package cc.ufinity.networkdiagnose.manager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import android.app.Activity;
import android.os.Handler;
import android.util.Log;
import cc.ufinity.networkdiagnose.util.HttpUtils;
import cc.ufinity.networkdiagnose.util.StringUtils;

/**
 * Web登录及下线认证测试类
 * 
 * @author zhirong
 * 
 */
public final class ChinaNetAuthManager extends AbstractManager {

    private Activity ctx;
    private Handler handler;
    private String paramStr ;
    private String userName;
    private String pwd;
    private String logonsessid;
    private String httpParamStr = "paramStr";
    private String prov;
    private String province;
    private Map<String, String> map = new HashMap<String, String>();
    
    private DBManager db;
    private ChinaNetLogoutParamStr account;
    
    private String ip;
    private String realIp;
    private String logoutParamStr;
    
    private long startTime;
    private long endTime;
    private String loginUrl = "https://wlan.ct10000.com/authServlet";
    private String qureryUrl = "https://wlan.ct10000.com/queryServlet?operate=authfailcount&username=18919665515&t";
    private String baseUrl = "https://wlan.ct10000.com";
    private String requestUrl;
    private String loginSecUrl;
    private String logoutUrl = "https://wlan.ct10000.com/logoutServlet?";
    private static final String TAG = "WebAuth"; 
    
    public ChinaNetAuthManager(Activity ctx) {
    	this.ctx = ctx;
    }

    
    /**
     * 登录用户下线
     * 
     * @return TRUE or False
     */
    public boolean logout() {
        boolean success = false;
        HttpClient client = HttpUtils.getSSLHttpClient();
        try {
            HttpPost post = new HttpPost(logoutUrl + Math.random());
            post.setEntity(new UrlEncodedFormEntity(setLogoutRequestParams(), "gb2312"));
            HttpResponse response = client.execute(post);
            int sc = response.getStatusLine().getStatusCode();
            String content = EntityUtils.toString(response.getEntity());
            System.out.println("断开网络返回状态："+sc);
            System.out.println("断开网络返回页面："+content);
            if (sc == HttpStatus.SC_OK) {
                if (content.contains("断开网络成功") || content.contains("下线成功")) {
                	System.out.println("断开网络成功！");
                	if(!canGotoWeb())
                		success = true;
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "下线认证出错", e);
        } finally {
            client.getConnectionManager().shutdown();
        }
        
        /*if(success) {
        	sendMsg(MessageWhat.LOGOUT_SUCCESS);
        } else {
        	sendMsg(MessageWhat.LOGOUT_FAILED);
        }*/
        return success;

    }
    
    /**
     * 登录用户下线
     * 
     * @return TRUE or False
     */
    public boolean logout2() {
        boolean success = false;
        HttpClient client = HttpUtils.getSSLHttpClient();
        try {
            HttpPost post = new HttpPost(logoutUrl + Math.random());
            post.setEntity(new UrlEncodedFormEntity(setLogoutRequestParams2(), "gb2312"));
            HttpResponse response = client.execute(post);
            int sc = response.getStatusLine().getStatusCode();
            String content = EntityUtils.toString(response.getEntity());
            System.out.println("断开网络返回状态："+sc);
            System.out.println("断开网络返回页面："+content);
            if (sc == HttpStatus.SC_OK) {
                if (content.contains("断开网络成功") || content.contains("下线成功")) {
                	System.out.println("断开网络成功！");
                	if(!canGotoWeb())
                		success = true;
                }
            } else {
            	if(!canGotoWeb())
            		success = true;
            }
        } catch (Exception e) {
            Log.e(TAG, "下线认证出错", e);
        } finally {
            client.getConnectionManager().shutdown();
        }
        
        /*if(success) {
        	sendMsg(MessageWhat.LOGOUT_SUCCESS);
        } else {
        	sendMsg(MessageWhat.LOGOUT_FAILED);
        }*/
        return success;

    }
    
    /**
     * 登录认证
     */
    public   boolean auth(String url, String userName, String pwd, String prov) {
    	 map.put("zx", "cw.zx.chntel.com");
         map.put("bj", "cw.bj.chntel.com");
         map.put("tj", "cw.tj.chntel.com");
         map.put("he", "cw.he.chntel.com");
         map.put("sx", "cw.sx.chntel.com");
         map.put("nm", "cw.nm.chntel.com");
         map.put("ln", "cw.ln.chntel.com");
         map.put("jl", "cw.jl.chntel.com");
         map.put("hl", "cw.hl.chntel.com");
         map.put("hb", "cw.hb.chntel.com");
         map.put("hn", "cw.hn.chntel.com");
         map.put("ha", "cw.ha.chntel.com");
         map.put("js", "cw.js.chntel.com");
         map.put("sd", "cw.sd.chntel.com");
         map.put("ah", "cw.ah.chntel.com");
         map.put("sh", "cw.sh.chntel.com");
         map.put("zj", "cw.zj.chntel.com");
         map.put("fj", "cw.fj.chntel.com");
         map.put("jx", "cw.jx.chntel.com");
         map.put("gd", "cw.gd.chntel.com");
         map.put("hi", "cw.hi.chntel.com");
         map.put("gx", "cw.gx.chntel.com");
         map.put("sc", "cw.sc.chntel.com");
         map.put("cq", "cw.cq.chntel.com");
         map.put("gz", "cw.gz.chntel.com");
         map.put("yn", "cw.yn.chntel.com");
         map.put("xz", "cw.xz.chntel.com");
         map.put("sn", "cw.sn.chntel.com");
         map.put("gs", "cw.gs.chntel.com");
         map.put("gh", "cw.gh.chntel.com");
         map.put("nx", "cw.nx.chntel.com");
         map.put("xj", "cw.xj.chntel.com");
         map.put("am", "cw.am.chntel.com");
         map.put("qg", "wlan.sh.chntel.com");
         map.put("udb", "189.cn");
         
    	System.out.println("url:"+url+"：用户名："+userName+"：密码："+pwd+"省："+prov);
    	System.out.println("开始web 认证");
        this.userName = userName;
        this.pwd = pwd;
        this.prov = prov;
        this.province = map.get(prov);
        boolean success = false;
        HttpClient client = HttpUtils.getSSLHttpClient();
        HttpGet get = new HttpGet(url);
        try {
            // 由于ChinaNet的WEB登陆是采用redirect方式，先获得redirect后地址所携带的参数值
            HttpResponse response = client.execute(get);
            int sc = response.getStatusLine().getStatusCode();
            String result = EntityUtils.toString(response.getEntity());
            System.out.println("redirect返回结果："+ result);
            Header []headers = response.getAllHeaders();
            System.out.println("redirect返回cookies：");
            for(int i=0; i<headers.length; i++){
            	System.out.println(headers[i].getName() + ": " +headers[i].getValue());
            }
            
            if ((sc == HttpStatus.SC_MOVED_TEMPORARILY) || sc == HttpStatus.SC_OK || (sc == HttpStatus.SC_MOVED_PERMANENTLY)
                    || (sc == HttpStatus.SC_SEE_OTHER) || (sc == HttpStatus.SC_TEMPORARY_REDIRECT))

            {
                // 解析各参数值
                Map<String, String> httpParams = parseLogonParams(result, "frame", "src");
               
                if(httpParams == null) {
                	//return authTwo(GlobalApp.loginurl,userName,pwd);
  //              	sendMsg(MessageWhat.LOGIN_FAILED);            ///登陆失败 ！！！！！！！！！
                	System.out.println("--------------       登陆失败    0              ----------------------");
                	return false;
                }
                paramStr = httpParams.get(this.httpParamStr);
                System.out.println("参数值"+paramStr);
                
                System.out.println("请求的地址："+baseUrl+requestUrl);
                get = new HttpGet(baseUrl+requestUrl);
                response = client.execute(get);
                result = EntityUtils.toString(response.getEntity());
                System.out.println("认证页面："+ result);
                headers = response.getAllHeaders();
              //  httpParams = parseLogonParamsLgout(result, "input", "value");
                //paramStr = httpParams.get(this.httpParamStr);
              //  System.out.println("认证页面参数值"+paramStr);
                // System.out.println("认证页面返回cookies：");
                for(int i=0; i<headers.length; i++){
                	System.out.println(headers[i].getName() + ": " +headers[i].getValue());
                }
                
                qureryUrl = "https://wlan.ct10000.com/queryServlet?operate=authfailcount&username=" 
                	+ userName + "&t";
                get = new HttpGet(qureryUrl + Math.random());
                get.setHeader("Content-Type", "application/x-www-form-urlencoded;");
                response = client.execute(get);
                result = EntityUtils.toString(response.getEntity());
                System.out.println("查询用户返回结果："+result);
                headers = response.getAllHeaders();
                System.out.println("查询用户返回结果cookies：");
                for(int i=0; i<headers.length; i++){
                	System.out.println(headers[i].getName() + ": " +headers[i].getValue());
                }
                
                String urlRnd = this.loginUrl +"?"+ Math.random();
                System.out.println("请求认证网址："+urlRnd);
                HttpPost  post = new HttpPost(urlRnd);
                post.setEntity(new UrlEncodedFormEntity(setRequestParams(), "gb2312"));
            //    post.setHeader("Content-Type", "application/x-www-form-urlencoded");
            //    post.setHeader("mimeType", "application/x-www-form-urlencoded");
            //    client = HttpUtils.getSSLHttpClient();
                response = client.execute(post);
                sc = response.getStatusLine().getStatusCode();
                System.out.println("authserver返回的状态："+sc);
                String content = EntityUtils.toString(response.getEntity());
                System.out.println("请求认证返回页面："+ content);
                headers = response.getAllHeaders();
                System.out.println("authserver返回cookies：");
                for(int i=0; i<headers.length; i++){
                	System.out.println(headers[i].getName() + ": " +headers[i].getValue());
                }
				if (sc == HttpStatus.SC_OK) {
				    //
					if (content.contains("登录成功")) {
						System.out.println("-----------------  保存登录信息       --------------      登录成功！");
						success = true;
						Map<String, String> logoutHttpParams = parseLogonParamsLgout(content, "input", "value"); 
						ip = logoutHttpParams.get("ip");
						realIp = logoutHttpParams.get("realIp");
						logoutParamStr = logoutHttpParams.get("paramStr");
						
						account.ip = ip;
						account.realIp = realIp;
						account.paramStr = realIp;
						db = new DBManager(ctx);
						db.saveChinaNetLogoutParamStr(account);
						db.release();
						
					}  else if (content.contains("登录失败")) {
						success = false;
						System.out.println("登录失败！");
					}
				} else if(canGotoWeb()){
						success = true;
						
						account = new ChinaNetLogoutParamStr();
						account.ip = ip;
						account.realIp = realIp;
						account.paramStr = realIp;
						db = new DBManager(ctx);
						db.saveChinaNetLogoutParamStr(account);
						db.release();
						System.out.println("登录成功！");
				}
            }

        } catch (Exception e) {
            Log.e(TAG, "Web登陆认证发生错误：", e);
        } finally {
            client.getConnectionManager().shutdown();
        }
        
        /*if(success) {
        	sendMsg(MessageWhat.LOGIN_SUCCESS);
        	System.out.println("--------------       登陆成功                  ----------------------");
        } else {
        	sendMsg(MessageWhat.LOGIN_FAILED);
        	System.out.println("--------------       登陆失败                  ----------------------");
        }*/
        return success;

        // return wh.CMCCLogin(userName, pwd);
    }

    public  boolean canGotoWeb()
    {
	    HttpClient client = HttpUtils.getSSLHttpClient(); 
        HttpGet get = new HttpGet("http://www.baidu.com");
        HttpResponse response;
		try {
			response = client.execute(get); 
			int sc = response.getStatusLine().getStatusCode();
			String content = EntityUtils.toString(response.getEntity());
			System.out.println(content);
	         if (sc == HttpStatus.SC_OK) {
	             if (content.contains("百度一下，你就知道 ")) {
	                 return true;
	             }
	         }
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
    	return false;
    }


    private Map<String, String> parseLogonParams(String content, String tag, String attr) {
        Map<String, String> httpParams = null;
        Document doc = Jsoup.parse(content);
        try {
        	Element e = doc.select(tag).get(1);
            System.out.println("------ parseLogonParams => Element:"+e.toString());
			// TODO: handle exception
	        if (e != null) {
	            String src = e.attr(attr);
	            System.out.println("scr"+src);
	            requestUrl = src;
	            httpParams = StringUtils.parseURLChinaNet(src);
        } 
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("========= parseLogonParams == " + e);
		}
        return httpParams;
    }
    
    
    private Map<String, String> parseLogonParamsLgout(String content, String tag, String attr) {
        Map<String, String> httpParams = new HashMap<String, String>();
        Document doc = Jsoup.parse(content);
        try {
        	for(int i=0; i<4; i++){
        		Element e = doc.select(tag).get(i);
              //   System.out.println("e:"+e.toString());
    			// TODO: handle exception
    	        if (e != null) {
    	            String value = e.attr(attr);
    	            String id = e.attr("id");
    	           //  System.out.println("id:"+id+"  value:"+value);
    	            httpParams.put(id, value);
        	}
        } 
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println(e);
		}
        return httpParams;
    }


    private List<NameValuePair> setRequestParams() {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("isChCardUser", "false" ));
        params.add(new BasicNameValuePair("isVerifycode", "false" ));
        params.add(new BasicNameValuePair("isWCardUser", "false" ));
        params.add(new BasicNameValuePair("paramStr", paramStr));
        params.add(new BasicNameValuePair("PassWord", pwd));
        params.add(new BasicNameValuePair("PassWord1", pwd ));
        params.add(new BasicNameValuePair("prov", prov ));
        params.add(new BasicNameValuePair("province", province));
        params.add(new BasicNameValuePair("UserName", userName));
        params.add(new BasicNameValuePair("UserName1", userName));
        params.add(new BasicNameValuePair("UserType", "1" ));
        
        params.add(new BasicNameValuePair("UserName2", "" ));
        params.add(new BasicNameValuePair("PassWord2", "" ));
        params.add(new BasicNameValuePair("verifycode", "" ));
        params.add(new BasicNameValuePair("verifycode1", "" ));
        params.add(new BasicNameValuePair("verifycode2", "" ));
        params.add(new BasicNameValuePair("randomCode", "" ));
        params.add(new BasicNameValuePair("randomCode2", "" ));        

        params.add(new BasicNameValuePair("roamName", "" ));
        
        return params;
    } 
    
    
    private List<NameValuePair> setLogoutRequestParams() {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("ip", ip ));
        params.add(new BasicNameValuePair("realIp", realIp ));
        params.add(new BasicNameValuePair("bOffline", "true" ));
        params.add(new BasicNameValuePair("paramStr", logoutParamStr));
        return params;
    } 
    
    private List<NameValuePair> setLogoutRequestParams2() {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        db = new DBManager(ctx);
        account = db.getChinaNetLogoutParamStr();
        db.release();
        params.add(new BasicNameValuePair("ip", account.ip));
        params.add(new BasicNameValuePair("realIp", account.realIp));
        params.add(new BasicNameValuePair("bOffline", "true" ));
        params.add(new BasicNameValuePair("paramStr", account.paramStr));
        return params;
    }

    public long getEndTime() {
        return endTime;
    }

    public void setEndTime(long endTime) {
        this.endTime = endTime;
    }

    public long getStartTime() {
        return startTime;
    }
    public void setStartTime(long startTime) {
        this.startTime = startTime;
    }

    public String getLogonsessid() {
        return logonsessid;
    }

    public void setLogonsessid(String logonsessid) {
        this.logonsessid = logonsessid;
    }
    
}
